package com.pdg.mcplugin.simpleconomy.dataproviders.accounts;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.pdg.mcplugin.common.interfaces.TableProviderValue;

public class AccountValue implements TableProviderValue<AccountValue>{
	public static final String FIELD_AMOUNT = "amount";
	public static final String FIELD_INITIAL = "initial";
	private static final double DEFAULT_VALUE = 0;
	private static final boolean DEFAULT_INITIAL = true;
	private static final String CREATE_FIELDS = "`"+FIELD_AMOUNT+"` REAL NOT NULL,`"+FIELD_INITIAL+"` INT NOT NULL";
	private static final String INSERT_FIELDS = "`"+FIELD_AMOUNT+"`,`"+FIELD_INITIAL+"`";
	private static final String INSERT_VALUES = "%f,%d";
	private static final String SELECT_LIST = "`"+FIELD_AMOUNT+"`,`"+FIELD_INITIAL+"`";
	private static final String UPDATE_LIST = "`"+FIELD_AMOUNT+"`=%f,`"+FIELD_INITIAL+"`=%d";
	private static final int INITIAL_FLAG_SET = 1;
	private static final int INITIAL_FLAG_CLEAR = 0;

	private double amount;
	private boolean initial;
	
	public AccountValue(double theAmount, boolean isInitial){
		setAmount(theAmount);
		setInitial(isInitial);
	}
	
	public void setInitial(boolean isInitial) {
		initial = isInitial;
	}
	
	public boolean isInitial(){
		return initial;
	}

	@Override
	public String getCreateFields() {
		return CREATE_FIELDS;
	}

	@Override
	public String getInsertFields() {
		return INSERT_FIELDS;
	}

	@Override
	public String getInsertValues() {
		return String.format(INSERT_VALUES,getAmount(),getInitialFlag());
	}

	private int getInitialFlag() {
		return isInitial()?INITIAL_FLAG_SET:INITIAL_FLAG_CLEAR;
	}

	@Override
	public String getSelectList() {
		return SELECT_LIST;
	}

	@Override
	public String getUpdateList() {
		return String.format(UPDATE_LIST,getAmount(),getInitialFlag());
	}

	@Override
	public AccountValue createValueFromResultSet(ResultSet theResultSet) {
		try {
			double theValue = theResultSet.getDouble(FIELD_AMOUNT);
			boolean isInitial = theResultSet.getBoolean(FIELD_INITIAL);
			return new AccountValue(theValue,isInitial);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static AccountValue defaultInstance(){
		return new AccountValue(DEFAULT_VALUE,DEFAULT_INITIAL);
	}

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

}
